<?php
namespace app\index\controller;

class Payres
{

    /**
     * 充值
     */
    function payresult()
    {
        $datas = $this->getXMLData();
        if ($datas['return_code'] == 'SUCCESS' && $datas['result_code'] == 'SUCCESS') {
            $pay = new \app\index\model\Payhistory();
             $res = $pay->getHistory($datas['out_trade_no']);
            if ($res && $res['status'] == 0) {
                $config = D('wxconfig');
                $cres = $config->find();
                if (! $cres) {
                    return;
                }
                $key = $cres['keys'];
                $signCheck = new \app\index\model\Signcheck();
                $signCheck->setKey($key);
                $ch = $signCheck->checkSign($datas);
                if (! $ch) {
                    return;
                }
                //处理逻辑
                $pay->finishHistory($res['id']);
                $pay = new \app\index\model\User();
                $pay->updateMoney($res['user_id'], $res['money'],true);
                return $signCheck->paySuccess(true);
            }
        }
    }

    function getXMLData()
    {
        /*
         * $path = 'ZLog/';
         * $chmod = 777;
         * if (! file_exists($path)) {
         * @mkdir($path);
         * @chmod($path, $chmod);
         * }
         * $file = 'ZLog/' . date('Y-m-d', time()) . '.txt';
         */
        $file_in = file_get_contents("php://input"); // 接收post数据
        
        $xml = simplexml_load_string($file_in); // 转换post数据为simplexml对象
        $datas = [];
        foreach ($xml->children() as $child) // 遍历所有节点数据
{
            $datas['' . $child->getName()] = '' . $child;
        }
        // @file_put_contents($file, json_encode($datas), FILE_APPEND);
        return $datas;
    }
}
